const db = require('../config/db');

/**
 * 操作日志中间件
 * 记录用户的操作行为
 */
const operationLog = (req, res, next) => {
  // 记录请求开始时间
  const startTime = Date.now();
  
  // 原始的res.end方法
  const originalEnd = res.end;
  
  // 重写res.end方法以捕获响应
  res.end = function(chunk, encoding) {
    // 调用原始的end方法
    originalEnd.call(res, chunk, encoding);
    
    // 记录操作日志
    recordOperationLog(req, res, startTime);
  };
  
  next();
};

/**
 * 记录操作日志
 */
async function recordOperationLog(req, res, startTime) {
  try {
    // 获取用户信息（如果已认证）
    let userId = null;
    let userName = 'Anonymous';
    
    if (req.user) {
      userId = req.user.id;
      userName = req.user.account || 'Unknown';
    }
    
    // 获取客户端IP
    const ipAddress = getClientIP(req);
    
    // 获取用户代理
    const userAgent = req.get('User-Agent') || '';
    
    // 计算执行时间
    const duration = Date.now() - startTime;
    
    // 过滤不需要记录的日志接口
    const excludePaths = ['/api/logs/list', '/api/logs/detail'];
    if (excludePaths.includes(req.path)) {
      return;
    }
    
    // 准备请求参数（过滤敏感信息）
    const requestParams = filterSensitiveData({ ...req.body, ...req.query });
    
    // 准备响应数据（仅记录基本状态信息）
    const responseData = {
      statusCode: res.statusCode
    };
    
    // 安全地将对象转换为JSON字符串
    let requestParamsJson = '{}';
    let responseDataJson = '{}';
    
    try {
      requestParamsJson = JSON.stringify(requestParams);
    } catch (error) {
      console.warn('序列化请求参数失败:', error);
      requestParamsJson = JSON.stringify({ error: '无法序列化请求参数' });
    }
    
    try {
      responseDataJson = JSON.stringify(responseData);
    } catch (error) {
      console.warn('序列化响应数据失败:', error);
      responseDataJson = JSON.stringify({ error: '无法序列化响应数据' });
    }
    
    // 插入日志记录
    await db.execute(
      `INSERT INTO operation_logs 
        (user_id, user_name, ip_address, method, url, user_agent, 
         request_params, response_data, status_code, duration) 
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        userId,
        userName,
        ipAddress,
        req.method,
        req.originalUrl,
        userAgent,
        requestParamsJson,
        responseDataJson,
        res.statusCode,
        duration
      ]
    );
    
    console.log(`操作日志已记录: ${req.method} ${req.originalUrl} (${duration}ms)`);
  } catch (error) {
    console.error('记录操作日志失败:', error);
  }
}

/**
 * 获取客户端真实IP
 */
function getClientIP(req) {
  return (
    req.headers['x-forwarded-for'] ||
    req.headers['x-real-ip'] ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    (req.connection.socket ? req.connection.socket.remoteAddress : null) ||
    'Unknown'
  ).split(',')[0].trim();
}

/**
 * 过滤敏感数据
 */
function filterSensitiveData(data) {
  const filtered = { ...data };
  const sensitiveKeys = ['password', 'token', 'authorization', 'auth'];
  
  for (const key in filtered) {
    if (sensitiveKeys.some(sensitiveKey => 
      key.toLowerCase().includes(sensitiveKey))) {
      delete filtered[key];
    }
  }
  
  return filtered;
}

module.exports = operationLog;